<?php
/**
 * @author 595949289@qq.com
 * @date 2023/9/4 8:49
 */

namespace CuiFox\oauth2server\controllers;

use Yii;
use yii\web\Controller;
use yii\web\HttpException;
use yii\web\Response;

class AuthorizeController extends Controller
{
    /**
     * @var bool
     */
    public $enableCsrfValidation = false;

    /**
     * @var \CuiFox\oauth2server\Module
     */
    public $module;

    /**
     * @return Response
     * @throws \ReflectionException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\di\NotInstantiableException
     * @throws \yii\web\ForbiddenHttpException
     */
    public function actionIndex()
    {
        $user = Yii::$app->user;
        if ($user->isGuest) {
            return $user->loginRequired();
        }
        $this->module->getServer()->handleAuthorizeRequest(null, null, !$user->isGuest, $user->id)->send();
    }

    /**
     * @throws \ReflectionException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\di\NotInstantiableException
     */
    public function actionToken()
    {
        $this->module->getServer()->handleTokenRequest()->send();
    }

    /**
     * @return array
     * @throws HttpException
     * @throws \ReflectionException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\di\NotInstantiableException
     */
    public function actionResource()
    {
        $server = $this->module->getServer();
        if (!$value = $server->verifyResourceRequest()) {
            $response = $server->getResponse();
            throw new HttpException($response->getStatusCode(), $response->getStatusText());
        }

        Yii::$app->response->format = Response::FORMAT_JSON;
        return [
            'success' => true,
            'message' => 'You accessed my APIs!',
        ];
    }

    /**
     * @return mixed
     * @throws \ReflectionException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\di\NotInstantiableException
     */
    public function actionCode()
    {
        $code = Yii::$app->request->post('code');
        Yii::$app->response->format = Response::FORMAT_JSON;
        return $this->module->getServer()->getStorage('authorization_code')->getAuthorizationCode($code);
    }
}